<?php
namespace app\common\middleware;

use app\common\exception\AdminException;
use think\Request;

class CrossDomain
{
    public function handle(Request $request, \Closure $next)
    {
//        throw new AdminException('进来');
        $origin = $request->header('origin');
        $whiteList = [
            'http://localhost:3000',
            'https://yourdomain.com',
        ];

        if (!in_array($origin, $whiteList)) {
            return response('Forbidden', 403);
        }

        $response = $next($request);

        $response->header([
            'Access-Control-Allow-Origin'      => $origin,
            'Access-Control-Allow-Methods'     => 'GET, POST, PUT, DELETE, OPTIONS',
            'Access-Control-Allow-Headers'     => 'Content-Type, Authorization, X-Requested-With, X-CSRF-TOKEN',
            'Access-Control-Allow-Credentials' => 'true',
            'Access-Control-Max-Age'           => 3600,
        ]);

        if ($request->method() === 'OPTIONS') {
            return response('', 204);
        }

        return $response;
    }
}